@model OrderListModel

@using Telerik.Web.Mvc.UI

@{
    var gridPageSize = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().GridPageSize;
    //var hideProfitReport = false;

    //page title
    ViewBag.Title = T("Admin.Orders").Text;
}

@using (Html.BeginForm("ExportExcelAll", "Order", FormMethod.Post, new { id = "post-form" }))
{
    <div class="section-header">
        <div class="title">
            <img src="@Url.Content("~/subsites/Administration/Content/images/ico-sales.png")" alt="" />
            @T("Admin.Orders")
        </div>
        @if (Model.CanManageAllStore)
        {
            <div class="options">
                <a href="@Url.Action("ExportXmlAll")" class="t-button">@T("Admin.Common.ExportToXml.All")</a>
                <input type="button" id="exportxml-selected" class="t-button" value="@T("Admin.Common.ExportToXml.Selected")" />
                <input type="button" id="exportexcel-all" class="t-button" value="@T("Admin.Common.ExportToExcel.All")" />
                <input type="button" id="exportexcel-selected" class="t-button" value="@T("Admin.Common.ExportToExcel.Selected")" />
            </div>
        }
    </div>
    <table>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.StartDate):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.StartDate)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.EndDate):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.EndDate)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.CustomerEmail):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.CustomerEmail)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.OrderKindId):
            </td>
            <td class="adminData">
                @Html.DropDownListFor(model => model.OrderKindId, Model.AvailableOrderKinds)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.DistrictId):
            </td>
            <td class="adminData">
                @Html.DropDownListFor(model => model.DistrictId, Model.AvailableDistricts)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.OrderStatusId):
            </td>
            <td class="adminData">
                @Html.DropDownList("OrderStatusId", Model.AvailableOrderStatuses)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.PaymentStatusId):
            </td>
            <td class="adminData">
                @Html.DropDownList("PaymentStatusId", Model.AvailablePaymentStatuses)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.ShippingStatusId):
            </td>
            <td class="adminData">
                @Html.DropDownList("ShippingStatusId", Model.AvailableShippingStatuses)
            </td>
        </tr>
        @if (Model.CanManageAllStore)
        {
            <tr>
                <td class="adminTitle">
                    @Html.NopLabelFor(model => model.SearchStoreId):
                </td>
                <td class="adminData">
                    @(Html.Telerik().ComboBoxFor(model => model.SearchStoreId)
                            .AutoFill(true)
                            .Filterable()
                            .DataBinding(binding => binding.Ajax().Select("StoreList", "Store", new { storeId = Model.SearchStoreId, customerId = 0 })))
                </td>
            </tr>

            <tr>
                <td class="adminTitle">
                    @Html.NopLabelFor(model => model.OrderGuid):
                </td>
                <td class="adminData">
                    @Html.EditorFor(model => Model.OrderGuid)
                </td>
            </tr>
        }
        else
        {
            @Html.HiddenFor(model => model.SearchStoreId)
        }

        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.GiftCardUsed):
            </td>
            <td class="adminData">
                @Html.CheckBoxFor(model => model.GiftCardUsed)
            </td>
        </tr>

        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.PickUpTime)
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.PickUpTime)
            </td>
        </tr>
    </table>
}

@using (Html.BeginForm("List", "Order"))
{
    <table>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.GoDirectlyToNumber):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => Model.GoDirectlyToNumber)
                <input type="submit" name="go-to-order-by-number" class="t-button" value="@T("Admin.Common.Go")" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="button" id="btnSearch" class="t-button" value="@T("Admin.Common.Search")" />
            </td>
        </tr>
    </table>
}

<p>
</p>
<table class="adminContent">
    <tr>
        <td>
            @(Html.Telerik().Grid<OrderModel>()
                        .Name("orders-grid")
                        .ClientEvents(events => events
                            .OnDataBinding("onDataBinding")
                            .OnDataBound("onDataBound")
                            .OnComplete("onComplete"))
                        .Columns(columns =>
                        {
                            columns.Bound(x => x.Id)
                            .ClientTemplate("<input type='checkbox' name='checkedRecords' value='<#= Id #>' class='checkboxGroups'/>")
                            .Title("<input id='mastercheckbox' type='checkbox'/>")
                            .Width(50)
                            .HtmlAttributes(new { style = "text-align:center" })
                            .HeaderHtmlAttributes(new { style = "text-align:center" });

                            columns.Bound(x => x.Id);
                            columns.Bound(x => x.OrderStatus);
                            columns.Bound(x => x.PaymentStatus);
                            columns.Bound(x => x.ShippingStatus);
                            columns.Bound(x => x.OrderKindStatus);
                            columns.Bound(x => x.CustomerEmail);
                            columns.Bound(x => x.CreatedOn).ClientTemplate("<#= CreatedOnStr #>");
                            columns.Bound(x => x.ShipmentDateString);
                            columns.Bound(x => x.ShipmentTimeRangeString);
                            columns.Bound(x => x.ShippingRateComputationMethodSystemName).Width(230);
                            columns.Bound(x => x.OrderTotal)
                                 .FooterTemplate(
                                 string.Format("<div><strong>{0}:</strong></div>" +
                                //(hideProfitReport ? "{1}" : "<div>{1}: <span id=\"aggregator-profit-block\"></span></div>") +
                                 "<div>{1}: <span id=\"aggregator-subtotal-block\"></span></div>" +
                                //"<div>{2}: <span id=\"aggregator-fuelsurcharge-block\"></span></div>" +
                                 "<div><span id=\"aggregator-tax-block\"></span></div>" +
                                 "<div>{2}: <span id=\"aggregator-total-block\"></span></div>",
                                 @T("Admin.Orders.Report.Summary").Text,
                                //(hideProfitReport ? "" : @T("Admin.Orders.Report.Profit").Text),
                                 @T("Admin.Orders.Report.SubtotalExclTax").Text,
                                //@T("Admin.Orders.Report.FuelSurcharge").Text,
                                 @T("Admin.Orders.Report.Total").Text)).FooterHtmlAttributes(new { colspan = 3 });
                            columns.Bound(x => x.HasGiftcardHistory);
                            columns.Bound(x => x.Id)
                                .Template(x => Html.ActionLink(T("Admin.Common.View").Text, "Edit", new { id = x.Id }))
                                .ClientTemplate("<a href=\"Edit/<#= Id #>\">" + T("Admin.Common.View").Text + "</a>")
                                .Width(50)
                                .Centered()
                                .Title(T("Admin.Common.View").Text);
                        })
                        .Pageable(settings => settings.PageSize(gridPageSize).Position(GridPagerPosition.Both))
                        .DataBinding(dataBinding => dataBinding.Ajax().Select("OrderList", "Order", Model))
                        .EnableCustomBinding(true))
        </td>
    </tr>
</table>

<script type="text/javascript">

    var selectedIds = [];
    var reportAggregates = "";
    var searchModel = [];

    $(document).ready(function () {

        //search button
        $('#btnSearch').click(function () {
            //search
            var grid = $('#orders-grid').data('tGrid');
            grid.currentPage = 1; //new search. Set page size to 1
            grid.ajaxRequest();
            //clear selected checkboxes
            $('.checkboxGroups').attr('checked', false).change();
            selectedIds = [];
            return false;
        });

        @if (Model.CanManageAllStore)
	        {
                <text>
        //"Export Excel selected" button
        $('#exportexcel-selected').click(function (e) {
            e.preventDefault();
            //redirect to required URL
            setLocation('@(Url.Action("ExportExcelSelected", "Order"))?selectedIds=' + selectedIds.join(","));
            return false;
        });

        //"Export Excel all" button
        $('#exportexcel-all').click(function (e) {
            e.preventDefault();
            //redirect to required URL

            var grid = $('#orders-grid').data('tGrid');
            grid.currentPage = 1; //new search. Set page size to 1
            grid.ajaxRequest();
            getValuesFromControls(); //get search result
            $('#post-form').submit();
            return false;
        });

        //"Export XML selected" button
        $('#exportxml-selected').click(function (e) {
            e.preventDefault();
            //redirect to required URL
            setLocation('@(Url.Action("ExportXmlSelected", "Order"))?selectedIds=' + selectedIds.join(","));
            return false;
        });
        </text>
	        }


        $('#mastercheckbox').click(function () {
            $('.checkboxGroups').attr('checked', $(this).is(':checked')).change();
        });

        //wire up checkboxes.
        $('#orders-grid input[type=checkbox][id!=mastercheckbox]').live('change', function (e) {
            var $check = $(this);
            if ($check.is(":checked") == true) {
                var checked = jQuery.inArray($check.val(), selectedIds);
                if (checked == -1) {
                    //add id to selectedIds.
                    selectedIds.push($check.val());
                }
            }
            else {
                var checked = jQuery.inArray($check.val(), selectedIds);
                if (checked > -1) {
                    //remove id from selectedIds.
                    selectedIds = $.grep(selectedIds, function (item, index) {
                        return item != $check.val();
                    });
                }
            }
            updateMasterCheckbox();
        });
    });

    function onDataBinding(e) {
        getValuesFromControls();
        e.data = searchModel;
    }

    function getValuesFromControls() {
        searchModel = {
            StartDate: $('#@Html.FieldIdFor(model => model.StartDate)').val(),
            EndDate: $('#@Html.FieldIdFor(model => model.EndDate)').val(),
            CustomerEmail: $('#@Html.FieldIdFor(model => model.CustomerEmail)').val(),
            OrderStatusId: $('#@Html.FieldIdFor(model => model.OrderStatusId)').val(),
            PaymentStatusId: $('#@Html.FieldIdFor(model => model.PaymentStatusId)').val(),
            ShippingStatusId: $('#@Html.FieldIdFor(model => model.ShippingStatusId)').val(),
            OrderGuid: $('#@Html.FieldIdFor(model => model.OrderGuid)').val(),
            OrderKindId: $('#@Html.FieldIdFor(model => model.OrderKindId)').val(),
            DistrictId: $('#@Html.FieldIdFor(model => model.DistrictId)').val(),
            SearchStoreId: $('#SearchStoreId').val(),
            GiftCardUsed: $('#@Html.FieldIdFor(model => model.GiftCardUsed)').prop("checked"),
            PickUpTime: $('#@Html.FieldIdFor(model => model.PickUpTime)').val()
        };
    }

    function onDataBound(e) {

        $('#orders-grid input[type=checkbox][id!=mastercheckbox]').each(function () {
            var currentId = $(this).val();
            var checked = jQuery.inArray(currentId, selectedIds);
            //set checked based on if current checkbox's value is in selectedIds.
            $(this).attr('checked', checked > -1);
        });

        updateMasterCheckbox();


    }

    function onComplete(e) {
        if (typeof e.response["Aggregates"] != "undefined") {
            updateAggregates(e.response["Aggregates"]);
        }
    }

    function updateAggregates(aggs) {
        for (var key in aggs) {

            @*@if (!hideProfitReport)
            {
                <text>$('#aggregator-profit-block').text(aggs['aggregatorprofit']);</text>
            }*@
            var str = "";
            for (var i = 0; i < aggs.aggregatortax.length; i++) {
                str += '<div>' + aggs.aggregatortax[i] + '</div>';
            }
            $("#aggregator-tax-block").html(str);
            $('#aggregator-subtotal-block').text(aggs['aggregatorsubtotalexcltax']);
            $('#aggregator-fuelsurcharge-block').text(aggs['aggregatorfuelsurcharge']);
            $('#aggregator-total-block').text(aggs['aggregatortotal']);
        }
    }

    function updateMasterCheckbox() {
        var numChkBoxes = $('#orders-grid input[type=checkbox][id!=mastercheckbox]').length;
        var numChkBoxesChecked = $('#orders-grid input[type=checkbox][checked][id!=mastercheckbox]').length;
        $('#mastercheckbox').attr('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);
    }
</script>

